package com.peng.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.base.exception.GuliException;
import com.peng.edu.entity.Chapter;
import com.peng.edu.entity.Video;
import com.peng.edu.entity.chapter.ChapterVo;
import com.peng.edu.entity.chapter.VideoVo;
import com.peng.edu.mapper.ChapterMapper;
import com.peng.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peng.edu.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Dengp
 * @since 2022-06-16
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    @Autowired
    private VideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideo(String courseId) {
        ArrayList<ChapterVo> result = new ArrayList<>();
        LambdaQueryWrapper<Chapter> queryWrapperChapter = new LambdaQueryWrapper<>();
        queryWrapperChapter.eq(Chapter::getCourseId,courseId);
        List<Chapter> chapterList = this.list(queryWrapperChapter);
        chapterList.stream().forEach(item->{
            ChapterVo chapterVo = this.getChapterIdAndVideo(item);
            result.add(chapterVo);
        });
        return result;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Video::getChapterId,chapterId);
        int count = videoService.count(queryWrapper);
        if (count>0){
            throw new GuliException(20001,"不能删除");
        }else {
            boolean b = this.removeById(chapterId);
            return b;
        }
    }

    //根据章节获取小节数据并封装
    private ChapterVo getChapterIdAndVideo(Chapter chapter) {
        ChapterVo chapterVo = new ChapterVo();
        BeanUtils.copyProperties(chapter,chapterVo);
        LambdaQueryWrapper<Video> queryWrapperVideo = new LambdaQueryWrapper<>();
        queryWrapperVideo.eq(Video::getChapterId,chapter.getId());
        List<Video> videoList = videoService.list(queryWrapperVideo);
        for (Video video : videoList) {
            VideoVo videoVo = new VideoVo();
            BeanUtils.copyProperties(video,videoVo);
            chapterVo.getChildren().add(videoVo);
        }
        return chapterVo;
    }
}
